#include "cmd_module.h"

#include <iostream>
#include <string>

#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
using namespace boost;
using namespace boost::asio;

#include "common/base/cmd_module_mgr.h"
#include "common/base/server_mgr.h"
#include "log/log.h"
#include "net/session.h"

/**
 * @desc 命令转发器
 * @param session 连接会话
 * @param fullCmd 命令，格式： moduleName@cmdName param1 param2 ...
 * @auth Qiwei.Gu
 * @date 2015-04-06 00:14:35
 */
bool ICmdModule::doDispatch(const std::shared_ptr<Session>& session,
                            const std::string& fullCmd)
{
    std::string cmd = fullCmd;
    auto cmdModuleMgr = ServerMgr::get().getMgr<CmdModuleMgr>(ManagerType::eCmdModule);
    if (!cmdModuleMgr)
    {
        LOG_ERROR("Cmd module manager not found,");
        return false;
    }

    if (cmd.empty())
    {
        LOG_WARN("cmd is null");
        return false;
    }

    boost::trim_left(cmd);
    boost::trim_right(cmd);

    std::string moduleName, cmdName, params;
    auto pos = cmd.find_first_of('@');
    if (pos != std::string::npos)
    {
        moduleName = cmd.substr(0, pos);
        cmd = cmd.substr(pos + 1);
    }
    if (moduleName.empty())
    {
        moduleName = "common";
    }

    pos = cmd.find_first_of(' ');
    cmdName = cmd.substr(0, pos);
    if (pos != std::string::npos)
    {
        params = cmd.substr(pos + 1);
    }

    auto module = cmdModuleMgr->getModule(moduleName);
    if (!module)
    {
        LOG_WARN("No fond cmd module" << moduleName);
        return false;
    }

    return module->doDispatch(session, cmdName, params);
}
